How to Secure Your Server with UFW and iptables: A Beginner's Guide to Linux Firewalls
Greetings, friends!
Configuring a network firewall is the primary and most vital step in securing any virtual server. Unprotected and open network ports quickly become targets for automated scanners, brute-force attacks, and exploitation attempts targeting system services.
In Linux operating systems, packet filtering is handled at the kernel level by the netfilter subsystem. To interact with it, administrators rely on two primary tools: the powerful, low-level iptables utility suite and UFW (Uncomplicated Firewall), a user-friendly wrapper designed to simplify daily administration. In this article, we will cover the fundamental operating principles of both solutions.
Key Takeaways: Core Conclusions
UFW is the standard for routine tasks: UFW offers a clean, human-readable syntax that prevents fatal configuration mistakes when opening ports for SSH, web servers, or databases on Ubuntu and Debian.
iptables provides low-level power:
iptablesgives you complete control over packet chains, Network Address Translation (NAT), port forwarding, and custom filtering rules at the kernel layer.The golden firewall rule is Default Deny: A robust firewall configuration follows a strict policy: "deny everything that is not explicitly allowed." All incoming traffic is blocked by default, except for essential services (such as SSH and HTTP/HTTPS).
Part 1. Setting Up UFW (Uncomplicated Firewall)
UFW comes pre-installed on Ubuntu and is readily available in the official repositories of most major Linux distributions.
Step 1: Check Status and Define Base Policy
Before enabling the firewall, set the default policies to block incoming connections and permit outgoing traffic:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 2: Allow Essential Ports
CRITICAL: Always allow SSH access before enabling UFW; otherwise, you will immediately lock yourself out of your server!
# Allow SSH on default port 22
sudo ufw allow 22/tcp
# Alternatively, allow SSH by service name
sudo ufw allow ssh
# Allow web traffic (HTTP & HTTPS)
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Step 3: Enable UFW and Manage Rules
# Enable the firewall
sudo ufw enable
# View current status and active rules with line numbers
sudo ufw status numbered
# Delete a rule by its corresponding number (e.g., rule #3)
sudo ufw delete 3
# Rate-limit SSH logins to mitigate brute-force attempts
sudo ufw limit ssh
Part 2. Understanding iptables Basics
iptables structures its logic using Tables and Chains. Standard packet filtering takes place within the filter table across three built-in chains:
INPUT: Traffic originating externally and destined directly for the server itself.
OUTPUT: Traffic generated locally by the server heading outward.
FORWARD: Traffic passing transitively through the server (e.g., when acting as a router or VPN gateway).
[ Network Packet ] ---> INPUT (Server) ---> FORWARD (Transit) ---> OUTPUT (Egress)
Essential iptables Commands
1. Inspect Active Rules
sudo iptables -L -v -n
-vprovides verbose output (showing byte and packet counters).-ndisplays IP addresses and port numbers numerically, bypassing DNS resolution delays.
2. Permit Loopback and Established Connections
The server must be able to communicate with itself via the loopback interface (lo) and maintain active state connections:
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
3. Open Specific Service Ports
# Allow incoming SSH connections (Port 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP (80) and HTTPS (443)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
4. Set Default Drop Policy
After explicitly accepting necessary connections, set the default chain policy to drop all other incoming traffic:
sudo iptables -P INPUT DROP
5. Reset All Rules (Flush)
If you accidentally lock a required port and need to clear your configuration back to defaults:
sudo iptables -F
sudo iptables -P INPUT ACCEPT
Comparison Matrix: UFW vs iptables
| Evaluation Criterion | UFW | iptables |
| Complexity Level | Low (intuitive, simple syntax) | Medium / High |
| Target Audience | Beginners and system administrators | Experienced engineers, DevOps, network architects |
| Configuration Flexibility | Tailored for common, standard scenarios | Complete (custom chains, packet marking, NAT, MANGLE) |
| NAT / Port Forwarding Support | Requires manually editing configuration files | Native support via the nat table |
| Rule Persistence | Yes (saves state automatically) | No (requires iptables-persistent package) |
FAQ: Frequently Asked Questions
Can I use UFW and iptables at the same time?
UFW operates as a user-friendly interface over
iptables(ornftablesin modern kernels). Manually modifyingiptablesrules while UFW is active is not recommended, as UFW reloads can overwrite your custom manual chains.What should I do if I lock myself out of SSH via iptables or UFW?
If you lose SSH access, open your hosting provider's management console and connect using the Emergency Console (VNC or Out-of-Band IPMI). Once logged in, disable the firewall using
sudo ufw disableor resetiptablesrules withsudo iptables -F.How do I make iptables rules persist across server reboots?
By default,
iptablesrules applied via the command line clear when the system restarts. To save them permanently on Ubuntu or Debian, install theiptables-persistentpackage:Bashsudo apt install iptables-persistent -y sudo netfilter-persistent save
Conclusion
A well-configured firewall forms the essential baseline for securing any server exposed to the internet. For 95% of routine web development and system administration tasks, UFW provides more than enough functionality. Meanwhile, iptables remains an indispensable tool for complex routing architectures and specialized packet filtering.
However, even the strictest firewall rules cannot protect your server if it faces massive volumetric network attacks (DDoS) at the carrier level that saturate your provider's network ports.
If you are looking for a secure, resilient infrastructure for your projects, explore NVMe VPS and Hourly Cloud Servers from MivoCloud. We provide pure KVM virtualization, guaranteed compute resources, a protected network infrastructure, and high-performance Enterprise NVMe storage to keep your services running flawlessly.
Article Author: Anatolie Cohaniuc

